"""
个人智能体管理服务
"""
from typing import List, Optional, Dict, Any, Tuple
from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.models.hiagent_models import (
    AppBriefInfo, PersonalAgent, ListOption, ListAppBriefsFilter,
    AppType, AgentMode
)


class PersonalAgentService:
    """个人智能体服务类"""
    
    def __init__(self, api_client: Optional[HiAgentAPIClient] = None):
        self.api_client = api_client or HiAgentAPIClient()
    
    def list_personal_agents(
        self,
        list_opt: Optional[ListOption] = None,
        filter_opt: Optional[ListAppBriefsFilter] = None,
        workspace_id: Optional[str] = None
    ) -> Tuple[List[AppBriefInfo], int]:
        """获取个人智能体列表 (workspace_id必填)"""
        if not workspace_id:
            raise ValueError("workspace_id is required and cannot be None")

        body = {}
        # WorkspaceID是必需参数
        body["WorkspaceID"] = workspace_id

        # 设置分页参数 - 根据HiAgent API文档,使用PageNumber和PageSize而不是Page
        if list_opt:
            list_opt_dict = {}
            if list_opt.page is not None:
                list_opt_dict["PageNumber"] = list_opt.page  # 修改: Page -> PageNumber
            if list_opt.page_size is not None:
                list_opt_dict["PageSize"] = list_opt.page_size
            if list_opt.sort_field:
                list_opt_dict["SortField"] = list_opt.sort_field
            if list_opt.sort_order:
                list_opt_dict["SortOrder"] = list_opt.sort_order

            if list_opt_dict:
                body["ListOpt"] = list_opt_dict
        
        # 设置筛选参数
        if filter_opt:
            filter_dict = {}
            if filter_opt.app_types:
                filter_dict["AppTypes"] = [app_type.value for app_type in filter_opt.app_types]
            if filter_opt.keyword:
                filter_dict["Keyword"] = filter_opt.keyword
            if filter_opt.is_published is not None:
                filter_dict["IsPublished"] = filter_opt.is_published
            if filter_opt.agent_mode:
                filter_dict["AgentMode"] = filter_opt.agent_mode.value
            
            if filter_dict:
                body["Filter"] = filter_dict
        
        response = self.api_client.make_request("ListAppBriefs", body)

        apps = []
        for item in response.get("Items", []):
            # API返回的字段是ID而不是AppID
            apps.append(AppBriefInfo(
                app_id=item.get("ID", ""),  # 修复：使用ID字段
                name=item.get("Name", ""),
                description=item.get("Description", ""),
                app_type=AppType(item.get("AppType", "Chat")),
                icon=item.get("Icon"),
                background=item.get("Background"),
                image=item.get("Image"),
                workspace_id=item.get("WorkspaceID"),
                created_time=item.get("CreateTime"),  # 修复：CreateTime而不是CreatedTime
                updated_time=item.get("UpdatedTime"),
                is_published=item.get("IsPublished"),
                agent_mode=AgentMode(item.get("DraftAgentMode", "Single")) if item.get("DraftAgentMode") else None  # 修复：使用DraftAgentMode
            ))
        
        total = response.get("Total", 0)
        return apps, total
    
    def get_personal_agent(self, app_id: str, workspace_id: Optional[str] = None) -> Optional[AppBriefInfo]:
        """获取个人智能体详情"""
        body = {
            "AppID": app_id,
            # WorkspaceID是必需参数
            "WorkspaceID": workspace_id or self.api_client.config.DEFAULT_WORKSPACE_ID
        }

        try:
            response = self.api_client.make_request("GetAppBrief", body)

            item = response.get("AppBriefInfo")
            if not item:
                return None

            # API返回的字段映射（与ListAppBriefs保持一致）
            return AppBriefInfo(
                app_id=item.get("ID", item.get("AppID", "")),  # 优先使用ID字段
                name=item.get("Name", ""),
                description=item.get("Description", ""),
                app_type=AppType(item.get("AppType", "Chat")),
                icon=item.get("Icon"),
                background=item.get("Background"),
                image=item.get("Image"),
                workspace_id=item.get("WorkspaceID"),
                created_time=item.get("CreateTime", item.get("CreatedTime")),  # 兼容两种字段名
                updated_time=item.get("UpdatedTime"),
                is_published=item.get("IsPublished"),
                agent_mode=AgentMode(item.get("DraftAgentMode", item.get("AgentMode", "Single"))) if item.get("DraftAgentMode") or item.get("AgentMode") else None
            )
        except Exception:
            return None
    
    def create_personal_agent(
        self,
        name: str,
        description: str,
        app_type: AppType,
        workspace_id: str,
        icon: Optional[str] = None,
        background: Optional[str] = None,
        image: Optional[str] = None,
        workflow_ids: Optional[List[str]] = None
    ) -> Optional[str]:
        """创建个人智能体 (workspace_id必填)"""
        if not workspace_id:
            raise ValueError("workspace_id is required and cannot be None")

        body = {
            "WorkspaceID": workspace_id,
            "Name": name,
            "AppType": app_type.value,
            "Description": description
        }

        if icon:
            body["Icon"] = icon

        if background:
            body["Background"] = background

        if image:
            body["Image"] = image

        if workflow_ids:
            body["WorkflowIDs"] = workflow_ids
        
        try:
            response = self.api_client.make_request("CreateApp", body)
            return response.get("AppID")
        except Exception as e:
            # 记录错误以便调试
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"CreateApp failed: {str(e)}")
            return None
    
    def update_personal_agent(
        self,
        app_id: str,
        name: Optional[str] = None,
        description: Optional[str] = None,
        icon: Optional[str] = None,
        background: Optional[str] = None,
        image: Optional[str] = None,
        http_runnable: Optional[bool] = None,
        api_runnable: Optional[bool] = None,
        workflow_ids: Optional[List[str]] = None,
        workspace_id: Optional[str] = None
    ) -> bool:
        """更新个人智能体"""
        body = {
            "AppID": app_id,
            # WorkspaceID是必需参数
            "WorkspaceID": workspace_id or self.api_client.config.DEFAULT_WORKSPACE_ID
        }
        
        if name is not None:
            body["Name"] = name
        
        if description is not None:
            body["Description"] = description
        
        if icon is not None:
            body["Icon"] = icon
        
        if background is not None:
            body["Background"] = background
        
        if image is not None:
            body["Image"] = image
        
        if http_runnable is not None:
            body["HTTPRunnable"] = http_runnable
        
        if api_runnable is not None:
            body["APIRunnable"] = api_runnable
        
        if workflow_ids is not None:
            body["WorkflowIDs"] = workflow_ids
        
        try:
            self.api_client.make_request("UpdateApp", body)
            return True
        except Exception as e:
            # 记录错误以便调试
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"UpdateApp failed: {str(e)}")
            return False
    
    def delete_personal_agent(self, app_id: str, workspace_id: Optional[str] = None) -> bool:
        """删除个人智能体"""
        body = {
            "AppID": app_id,
            # WorkspaceID是必需参数
            "WorkspaceID": workspace_id or self.api_client.config.DEFAULT_WORKSPACE_ID
        }

        try:
            self.api_client.make_request("DeleteApp", body)
            return True
        except Exception as e:
            # 记录错误以便调试
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"DeleteApp failed: {str(e)}")
            return False

    def copy_personal_agent(self, from_app_id: str, workspace_id: Optional[str] = None) -> Optional[str]:
        """复制个人智能体

        Raises:
            Exception: 复制失败时抛出异常，包含详细错误信息
        """
        body = {
            "FromAppID": from_app_id,
            # WorkspaceID是必需参数
            "WorkspaceID": workspace_id or self.api_client.config.DEFAULT_WORKSPACE_ID
        }

        try:
            response = self.api_client.make_request("CopyApp", body)
            return response.get("AppID")
        except Exception as e:
            # 记录错误以便调试
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"CopyApp failed: {str(e)}")

            # 解析错误信息，提供更友好的提示
            error_msg = str(e)
            if "部分组件需调整" in error_msg or "需调整、发布" in error_msg:
                friendly_msg = "智能体配置不完整，无法复制。请先为智能体配置模型、提示词等必要组件，并保存草稿配置。"
                logger.error(f"配置不完整: {friendly_msg}")
                raise Exception(friendly_msg)
            else:
                # 抛出原始异常信息
                raise Exception(f"复制智能体失败: {error_msg}")
    
    def check_agent_name(self, name: str, app_id: Optional[str] = None, workspace_id: Optional[str] = None) -> bool:
        """检查智能体名称是否重复"""
        body = {
            "Name": name,
            # WorkspaceID是必需参数
            "WorkspaceID": workspace_id or self.api_client.config.DEFAULT_WORKSPACE_ID
        }

        if app_id:
            body["AppID"] = app_id

        try:
            response = self.api_client.make_request("CheckAppByName", body)
            return not response.get("Reduplicated", False)
        except Exception:
            return False
    
    def copy_from_app_center(
        self,
        src_app_id: str,
        target_workspace_id: Optional[str] = None,
        dst_app_name: Optional[str] = None
    ) -> Optional[str]:
        """从应用中心复制智能体"""
        body = {
            "SrcAppID": src_app_id,
            "CopyScene": "AppCenter"
        }
        
        if target_workspace_id:
            body["TargetWorkspaceID"] = target_workspace_id
        
        if dst_app_name:
            body["DstAppName"] = dst_app_name
        
        try:
            response = self.api_client.make_request("CopyAppFromAppCenter", body)
            return response.get("AppID")
        except Exception:
            return None